package com.atguigu.gmallsugar.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmallsugar.bean.Kw;
import com.atguigu.gmallsugar.bean.Traffic;
import com.atguigu.gmallsugar.mapper.TrafficMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class TrafficServiceImpl implements TrafficService {
    
    @Autowired
    TrafficMapper trafficMapper;
    
    @Override
    public String statTraffic(Integer date) {
        
        List<Traffic> list = trafficMapper.stat(date);
        
        // 把数据封装到 map 中: key=hour, value=traffic
        HashMap<Integer, Traffic> hourToTrafficMap = new HashMap<>();
        for (Traffic traffic : list) {
            hourToTrafficMap.put(traffic.getHour(), traffic);
        }
        
        
        JSONObject result = new JSONObject();
        result.put("status", 0);
        result.put("msg", "");
        
        JSONObject data = new JSONObject();
        
        JSONArray categories = new JSONArray();
        for (int hour = 0; hour < 24; hour++) {
            categories.add(hour);
        }
        data.put("categories", categories);
        
        JSONArray series = new JSONArray();
        
        JSONObject pv = new JSONObject();
        pv.put("name", "pv");
        JSONArray pvData = new JSONArray();
        pv.put("data", pvData);
        series.add(pv);
        
        JSONObject uv = new JSONObject();
        uv.put("name", "uv");
        JSONArray uvData = new JSONArray();
        uv.put("data", uvData);
        series.add(uv);
        
        JSONObject sv = new JSONObject();
        sv.put("name", "sv");
        JSONArray svData = new JSONArray();
        sv.put("data", svData);
        series.add(sv);
        
        
        data.put("series", series);
        
        
        for (int hour = 0; hour < 24; hour++) {
            Traffic traffic = hourToTrafficMap.getOrDefault(hour,
                                                            new Traffic(hour, 0L, 0L, 0L)
            );
            pvData.add(traffic.getPv());
            uvData.add(traffic.getUv());
            svData.add(traffic.getSv());
        }
        result.put("data", data);
        return result.toJSONString();
    }
    
    @Override
    public String kw(Integer date) {
        List<Kw> list = trafficMapper.kw(date);
    
        JSONObject result = new JSONObject();
        result.put("status", 0);
        result.put("msg", "");
    
        JSONArray data = new JSONArray();
    
        for (Kw kw : list) {
            JSONObject obj = new JSONObject();
            obj.put("name", kw.getKeyword());
            obj.put("value", kw.getCount());
    
            data.add(obj);
        }
    
        
        result.put("data", data);
        return result.toJSONString();
    }
    
}
